<template>
  <a-card :bordered="false">
    <!-- 检索区域 -->
    <div class="table-page-search-wrapper">
      <!-- 检索条件区域 -->
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xxl="5" :xl="8">
            <a-form-item label="报告主题" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }">
              <a-select placeholder="请选择报告主题" allowClear v-model="queryParams.theme" @change="themeChange">
                <a-select-option v-for="item in themeData" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xxl="5" :xl="8">
            <a-form-item label="统计方式" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }">
              <a-radio-group v-for="item in statisticalModeData" :key="item.id" :disabled="statisticalModeDisabled" v-model="queryParams.statisticalMode" @change="statisticalModeChange">
                <a-radio :value="item.value">{{ item.name }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :xxl="5" :xl="8" v-show="!queryParams.statisticalMode || queryParams.statisticalMode === '1'">
            <a-form-item label="时间范围" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }">
              <a-range-picker allowClear style="width: 100%;" v-model="queryParams.timeRange" />
            </a-form-item>
          </a-col>
          <a-col :xxl="5" :xl="8" v-show="!queryParams.statisticalMode || queryParams.statisticalMode === '2'">
            <a-form-item label="考核对象" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }">
              <a-tree-select
                ref="statisticalTarget"
                placeholder="请选择考核对象"
                allowClear
                showSearch
                treeCheckable
                treeCheckStrictly
                treeDefaultExpandAll
                style="width: 100%;"
                :maxTagCount="1"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :replaceFields="{children:'children', title:'title', key:'value', value: 'value' }"
                :treeData="statisticalTargetData"
                :filterTreeNode="filterTreeData"
                v-model="queryParams.statisticalTarget"
              />
            </a-form-item>
          </a-col>
          <a-col :xxl="4" :xl="12">
            <a-button type="primary" @click="searchQuery">查询</a-button>
            <a-button type="default" style="margin-left: 8px;" @click="exportReport">导出报表</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 表格区域 -->
    <div>
      <a-table
        defaultExpandAllRows
        :key="reportTableKey"
        :pagination="false"
        :loading="reportTableDataLoading"
        :columns="reportTableColumns"
        :childrenColumnName="'childList'"
        :rowKey="'id'"
        :dataSource="reportTableData"
        :scroll="{ x: 1200 }" />
    </div>
  </a-card>
</template>

<script>
import { getAction, postAction, downFile } from '@/api/manage'

// 报告指标信息项对象参数
const titleColumnObject = {
  title: '指标信息',
  dataIndex: 'name',
  key: 'name',
  align: 'left',
  fixed: 'left'
}
// 报告合计项对象参数
const totalColumnObject = {
  title: '合计',
  dataIndex: 'total',
  key: 'total',
  width: '100',
  align: 'center'
}

export default {
  name: 'EvaluatingReport',
  data() {
    return {
      queryParams: {
        theme: undefined, // 主题
        statisticalMode: '1', // 统计方式
        timeRange: undefined, // 时间范围
        statisticalTarget: undefined // 考核对象
      }, // 查询对象参数
      themeData: [], // 报告主题数据数组参数
      statisticalModeData: [
        {
          id: 1,
          name: '按数据期',
          value: '1'
        },
        {
          id: 2,
          name: '按考核对象',
          value: '2'
        }
      ], // 统计方式静态数据
      statisticalModeDisabled: false, // 统计方式选择可用性参数，默认为false
      statisticalTargetData: [], // 考核对象数据数组参数
      reportTableKey: 0, // 报告表格key参数
      reportTableColumns: [
        titleColumnObject,
        {
          title: '指标详情',
          dataIndex: '',
          key: 'content',
          align: 'center'
        },
        totalColumnObject
      ], // 报告表格表头参数
      reportTableData: [], // 报告表格数据
      reportTableDataLoading: false, // 报告表格数据加载参数
      url: {
        evaluationList: '/eval/scSituationEval/rootList',
        assessObjectList: '/eval/scSituationEval/listDimensionValue',
        getReportIndexColumns: '/eval/scSituationEval/transDimension',
        getReport: '/eval/scSituationEval/queryPoiTree',
        exportReport: '/eval/scSituationEval/exportReport'
      }
    }
  },
  created() {
    this.loadThemeData() // 初始加载报告主题数据
  },
  methods: {
    // 获取加载报告主题数据
    loadThemeData() {
      getAction(this.url.evaluationList, { status: 1, pid: 0 }).then(res => {
        if (res.success) {
          this.themeData = res.result.records
        } else {
          this.themeData = []
        }
      })
    },
    // 报告主题选择变更事件绑定
    themeChange(value, obj) {
      console.log(value, obj)
      this.statisticalModeDisabled = false // 重置统计方式选择可用性参数为false
      this.statisticalTargetData = [] // 重置考核对象数据数组参数为空
      this.queryParams.statisticalTarget = undefined // 重置考核对象对应的查询参数
      this.reportTableKey = 0 // 重置报告表格key为0
      if (!value) {
        delete titleColumnObject.width
        this.reportTableColumns = [
          titleColumnObject,
          {
            title: '指标详情',
            dataIndex: '',
            key: 'content',
            align: 'center'
          },
          totalColumnObject
        ] // 报告表格表头重置
        this.reportTableData = [] // 报告表格数据重置
      } else {
        this.getThemeBindingQueryType(value) // 选择值变更时，重新获取当前报告主题对应的查询类型
      }
    },
    // 查询获取指定报告主题对应的查询类型情况
    getThemeBindingQueryType(id) {
      // 从主题数据中筛选获取选中项
      const matchingData = this.themeData.filter(item => {
        return item.id === id
      })
      const statisticalMode = matchingData[0].evalCycle === null ? '2' : '1'
      this.statisticalModeDisabled = true // 设置统计方式选择可用性参数为true
      if (this.queryParams.statisticalMode !== statisticalMode) {
        this.queryParams.statisticalMode = statisticalMode
        this.statisticalModeChange()
      }
      this.queryParams.statisticalTarget = undefined
      if (matchingData[0].evalObject !== null) {
        this.$refs.statisticalTarget.$el.click() // 触发下拉面板展开，避免出现渲染异常
        getAction(this.url.assessObjectList, { dimensionTypeId: matchingData[0].evalObject }).then((res) => {
          if (res.success) {
            this.statisticalTargetData = res.result
          } else {
            this.statisticalTargetData = []
          }
        })
      }
    },
    // 统计方式选择变更事件绑定
    statisticalModeChange() {
      this.queryParams.timeRange = undefined // 重置当前时间范围查询参数
    },
    filterTreeData(value, treeNode) {
      return treeNode.data.props.title.indexOf(value) >= 0 // 模糊匹配筛选
    },
    // 根据检索条件查询
    searchQuery() {
      if (!this.checkQueryParamsIntegrality()) return // 检查检索条件的完整性
      this.getReportData() // 获取查询结果
    },
    // 获取查询报告结果
    async getReportData() {
      this.reportTableDataLoading = true
      // 获取报告表头
      const getReportIndexColumnsResult = await postAction(this.url.getReportIndexColumns, this.getParams())
      if (!getReportIndexColumnsResult.success) {
        this.reportTableDataLoading = false
        return
      }
      let widthSettingFlag = false // 维度列宽设置标识
      if (Object.keys(getReportIndexColumnsResult.result).length > 10) widthSettingFlag = true // 维度列数量超过10时，列宽设置标识变更为true
      // 格式化指标列表头
      const reportIndexColumns = []
      for (const key in getReportIndexColumnsResult.result) {
        const currentIndexColumn = {
          title: getReportIndexColumnsResult.result[key],
          dataIndex: key,
          key: key,
          align: 'center'
        }
        if (widthSettingFlag) currentIndexColumn.width = 150 // 设置列宽
        reportIndexColumns.push(currentIndexColumn)
      }
      // 获取报告数据
      let getReportData = []
      postAction(this.url.getReport, this.getParams()).then((res) => {
        if (res.success) {
          getReportData = res.result
          titleColumnObject.width = 240 + 20 * getReportData[0].depth // 设置报告指标项宽度(基础240，单位扩展20，扩展度为数据深度)
          this.formatReportData(getReportData) // 格式化报告数据
        }
        this.reportTableColumns = [titleColumnObject, ...reportIndexColumns] // 设置报告表头
        this.reportTableKey = 1 // 变更报告表格key为1(用于表格展开)
        this.reportTableData = getReportData // 回显报告数据
        this.reportTableDataLoading = false
      })
    },
    // 格式化报告数据
    formatReportData(origin) {
      for (const item of origin) {
        if (item.childList.length) {
          this.formatReportData(item.childList)
        } else if (item.indexVos.length) {
          for (const subItem of item.indexVos) {
            const temp = {}
            temp.id = `${item.id}${subItem.id}`
            temp.name = `${subItem.showName || subItem.name}(单位:${subItem.unit || '--'})`
            Object.assign(temp, temp, subItem.indexData)
            item.childList.push(temp)
          }
        }
      }
    },
    // 导出报告
    exportReport() {
      if (!this.checkQueryParamsIntegrality()) return // 检查检索条件的完整性
      const { name } = this.themeData.find(item => item.id === this.queryParams.theme)
      const fileName = '评价报告-' + name
      downFile(this.url.exportReport, { JSONBody: JSON.stringify(this.getParams()) }).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      })
    },
    // 获取查询对象参数
    getParams(type = 1) {
      const params = {}
      params.evalId = this.queryParams.theme
      params.isDate = this.queryParams.statisticalMode === '1' ? '1' : '0'
      let dimensionValues = []
      if (this.queryParams.timeRange) dimensionValues = [this.queryParams.timeRange[0].format('YYYYMMDD').toString(), this.queryParams.timeRange[1].format('YYYYMMDD').toString()]
      if (this.queryParams.statisticalTarget) {
        dimensionValues = this.queryParams.statisticalTarget.map(item => {
          return item.value
        })
      }
      params.dimensionValues = dimensionValues
      if (type === 2) params.dimensionValues = params.dimensionValues.toString()
      return params
    },
    // 验证检索查询条件完整性
    checkQueryParamsIntegrality() {
      if (!this.queryParams.theme) {
        this.$message.warning('请选择报告主题!')
        return false
      }
      if (!this.queryParams.statisticalMode) {
        this.$message.warning('请选择统计方式!')
        return false
      }
      if (this.queryParams.statisticalMode === '1' && (!this.queryParams.timeRange || this.queryParams.timeRange && this.queryParams.timeRange.length === 0)) {
        this.$message.warning('请选择时间范围!')
        return false
      }
      if (this.queryParams.statisticalMode === '2' && (!this.queryParams.statisticalTarget || this.queryParams.statisticalTarget && this.queryParams.statisticalTarget.length === 0)) {
        this.$message.warning('请选择考核对象!')
        return false
      }
      return true
    }
  }
}
</script>

<style scoped>
  @import '~@assets/less/common.less';
</style>
